//
//  GGTCityListViewController.m
//  GGT
//
//  Created by Vision on 14-10-28.
//  Copyright (c) 2014年 GGT. All rights reserved.
//

#import "GGTCityListViewController.h"
#import "GGTAppDelegate.h"
#import "GGTTeamBuyViewController.h"
#import "MBProgressHUD.h"

@interface GGTCityListViewController ()<UITableViewDataSource,UITableViewDelegate,DPRequestDelegate, UISearchBarDelegate , UISearchDisplayDelegate>
//城市列表tableView
@property (nonatomic, retain) UITableView *cityTableView;
//城市数组
@property (nonatomic, retain) NSArray *cityArr;
//热门城市数组
@property (nonatomic, retain) NSMutableArray *hotCityArr;
//索引以及组内容数组
@property (nonatomic, retain) NSArray *groupTitleArr;
@property (nonatomic, retain) NSMutableArray *letterArr;
@property (nonatomic, retain) NSMutableArray *tempArr;
//定位按钮
@property (nonatomic, retain) UIButton *localButton;
//搜索栏
@property (nonatomic, retain) UISearchBar *mySearchBar;
//配套uiSearchDisplayController
@property (nonatomic, retain) UISearchDisplayController *mySearchDisplayController;
//搜索数据
@property (nonatomic, retain) NSArray *searchData;
//搜索状态
@property (nonatomic, assign) BOOL isSearch;
//MBProgressHUD
@property (nonatomic, retain) MBProgressHUD *hud;
@end

@implementation GGTCityListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //数组初始化
        self.cityArr = [NSArray array];
        self.hotCityArr = [NSMutableArray array];
        self.letterArr = [NSMutableArray array];
        self.tempArr = [NSMutableArray array];
        self.searchData = [NSArray array];
        self.isSearch = NO;
        
        self.groupTitleArr = @[@"热门",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",];
        //HUB
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.labelText = @"获取城市信息";
        [self.hud setMode:MBProgressHUDModeIndeterminate];
        
        
        //网络数据请求
        NSString *url = @"v1/metadata/get_cities_with_deals";
        NSString *params = @"";
        [[[GGTAppDelegate instance] dpapi] requestWithURL:url paramsString:params delegate:self];
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //搜索栏
    //searchBar
    
    self.mySearchBar = [[UISearchBar alloc] init];
    self.mySearchBar.frame =CGRectMake(0,0, self.view.frame.size.width ,44);
    self.mySearchBar.delegate =self;
    self.mySearchBar.placeholder =@"输入城市名称或关键字查询";
    
    //SearchDisplayController
    
    
    self.mySearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.mySearchBar contentsController:self];
    self.searchDisplayController.delegate =self;
    self.mySearchDisplayController.searchResultsTableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.mySearchDisplayController.searchResultsDataSource =self;
    self.mySearchDisplayController.searchResultsDelegate =self;
    [self.mySearchDisplayController.searchResultsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cityTableView"];
    
    
    
    //定位按钮
    self.localButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.localButton.frame = CGRectMake(0, 64, self.view.frame.size.width - 60, 44);
    NSString *city = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"];
    [self.localButton setTitle:[NSString stringWithFormat:@"当前选中城市:%@",city] forState:UIControlStateNormal];
    [self.localButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.localButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:self.localButton];
    
    //取消按钮
    UIButton * cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    cancelButton.frame = CGRectMake(self.view.frame.size.width - 60, 64, 60, 44);
    [cancelButton setTitle:@"返回" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelButton];
    
    //主tableView
    self.cityTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 108, self.view.frame.size.width, self.view.frame.size.height - 108) style:UITableViewStyleGrouped];
    self.cityTableView.delegate = self;
    self.cityTableView.dataSource = self;
    [self.view addSubview:self.cityTableView];
    [self.cityTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cityTableView"];
    self.cityTableView.sectionIndexColor = [UIColor blackColor];
    // self.cityTableView.tableHeaderView = self.mySearchBar;
    self.searchDisplayController.displaysSearchBarInNavigationBar = YES;
}

//取消按钮
- (void)buttonClicked:(UIBarButtonItem *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}


//数据处理
#pragma mark - 豆瓣解析数据回调函数
- (void)request:(DPRequest *)request didFailWithError:(NSError *)error
{
    //self.resultTextView.contentOffset = CGPointZero;
    NSLog(@"注意参数或地址填写错误:%@",[error description]);
    
}
- (void)request:(DPRequest *)request didFinishLoadingWithResult:(id)result
{
    //self.resultTextView.contentOffset = CGPointZero;
    //NSLog(@"%@", request.getURL);
    //解析城市数据
    self.cityArr = [result objectForKey:@"cities"];
    for (int i = 0; i < 10; i++) {
        [self.hotCityArr addObject:[self.cityArr objectAtIndex:i]];
    }
    //将城市名处理成拼音(目前有多音字bug)
    for (NSString *str in self.cityArr) {
        NSMutableString *ms = [[NSMutableString alloc] initWithString:str];
        if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
            
        }
        if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)) {
            //NSString *mStr = [[ms substringToIndex:1] uppercaseString];
            NSDictionary *dic = @{ms: str};
            [self.letterArr addObject:dic];
            
        }
        
    }
    [ self.letterArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDictionary * dic1 = (NSDictionary *)obj1;
        NSDictionary * dic2 = (NSDictionary *)obj2;
        
        return [[[dic1 allKeys]lastObject] compare:[[dic2 allKeys] lastObject]];
    }];
    /*    for (int i = 0; i < self.letterArr.count; i++) {
     NSDictionary *dic = self.letterArr[i];
     for (NSString *key in dic) {
     NSLog(@"%@ : %@", key, [dic valueForKey:key] );
     }
     }
     for (int i = 0; i < 26; i++) {
     
     for (NSDictionary * temp in self.letterArr) {
     if ([[[temp allKeys] lastObject] hasPrefix:[NSString stringWithFormat:@"%c",96 + i]] == YES ) {
     
     
     }
     }
     
     }
     */
    //将处理好的数据排序加入字典
    for (int i = 0; i < 26; i ++) {
        NSMutableArray *array = [NSMutableArray array];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.letterArr];
        for (NSDictionary *dic in arr) {
            
            if ([[[dic allKeys] lastObject] hasPrefix:[NSString stringWithFormat:@"%c",97 + i]] == YES ) {
                [array addObject:[[dic allValues] lastObject]];
                [self.letterArr removeObject:dic];
                //NSLog(@"6666%@", [[dic allKeys] lastObject]);
                
            }
        }
        
        [self.tempArr addObject:array];
    }
    
    [self.cityTableView reloadData];
    [self.hud hide:YES];
}


#pragma mark - tableView函数回调函数
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 25;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //判断是否处于搜索状态 (同时处理热门城市)
    if (self.isSearch) {
        return self.searchData.count;
    } else {
        if (section == 0) {
            return self.hotCityArr.count;
        } else {
            
            if (self.tempArr.count != 0) {
                
                return  [[self.tempArr objectAtIndex:section - 1] count];
            }
            return 0;
        }
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cityTableView"];
    
    if(self.isSearch)
	{
		// 使用searchData作为表格显示的数据
		cell.textLabel.text = [self.searchData objectAtIndex:indexPath.row];
        
    }
	else{
        if (indexPath.section == 0) {
            cell.textLabel.text = self.hotCityArr[indexPath.row];
            return cell;
        }
        cell.textLabel.text = [self.tempArr[indexPath.section - 1] objectAtIndex:indexPath.row];
	}
    
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.isSearch) {
        return 1;
    }else {
        return self.groupTitleArr.count;
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.isSearch) {
        return @"搜索结果";
    } else {
        return self.groupTitleArr[section];
    }
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (self.isSearch) {
        return nil;
    } else {
        return self.groupTitleArr;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //NSLog(@"%@",cell.textLabel.text);
    //存入数据库
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:cell.textLabel.text forKey:@"cityName"];
    [userDefaults synchronize];
    //发送通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"cesuo" object:nil userInfo:nil];
    
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
#pragma mark - 搜索相关
- (void) searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
    self.isSearch = NO;
}
// UISearchBarDelegate定义的方法，单击取消激发
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
	// 取消搜索状态
    self.isSearch = NO;
}
// UISearchBarDelegate定义的方法，索文本框内文本改变时激发
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	// 调用filterBySubstring:方法执行搜索
	[self filterBySubstring:searchText];
}
// UISearchBarDelegate定义的方法，单击Search激发
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
	// 调用filterBySubstring:方法执行搜索
	[self filterBySubstring:searchBar.text];
	[searchBar resignFirstResponder];
}
- (void) filterBySubstring:(NSString*) subStr
{
    
	self.isSearch = YES;
	NSPredicate* pred = [NSPredicate predicateWithFormat:
                         @"SELF CONTAINS[c] %@" , subStr];
	self.searchData = [self.cityArr filteredArrayUsingPredicate:pred];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
